﻿using System;
using System.Web;
using System.Web.Mvc;
using Repository;
using UI.Helper;

namespace UI.Areas.Admin.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Admin/Home/

        public ActionResult Index()
        {
            if (Request.Cookies[Constants.USER_SESSION] != null)
                return RedirectToAction("Index", "FurnitureCategory");

            return View();
        }

        public ActionResult LogOut()
        {
            if (Response.Cookies[Constants.USER_SESSION] != null)
            {
                Response.Cookies[Constants.USER_SESSION].Expires = DateTime.Now.AddDays(-1);
                Response.Cookies[Constants.USER_ID_SESSION].Expires = DateTime.Now.AddDays(-1);
            }

            return RedirectToAction("Index");
        }

        public ActionResult LogIn(FormCollection collection)
        {
            string userName = collection["username"].ToString();

            string password = collection["password"].ToString();

            var repository = RepositoryManager.CreateUserRepository();

            var objUser = repository.GetUserByUserName(userName);

            if (objUser != null)
            {
                //check password
                if (objUser.Password == password)
                {
                    //continute check role of user
                    Response.Cookies.Add(new HttpCookie(Constants.USER_SESSION, "true"));
                    Response.Cookies.Add(new HttpCookie(Constants.USER_ID_SESSION, objUser.Id.ToString()));
                    return RedirectToAction("Index", "FurnitureCategory");
                }
                else
                {
                    TempData[Constants.MESSAGE] = "Mật khẩu chưa đúng.";
                }
            }
            else
            {
                TempData[Constants.MESSAGE] = "Tên đăng nhập chưa đúng.";
            }

            return RedirectToAction("Index");
        }
    }
}